const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
// routes methods
app.get("/", (req, res) => {
  res.send("Hello World with express");
});
app.post("/", (req, res) => {
  res.send("Got a POST request");
});

app.all("/secrets", (req, res) => {
  res.send("This is a secret area, shhhh!");
});
app.all("/secrets", (req, res, next) => {
  console.log("This is a middleware function");
  next();
});
// 基于字符串的路由路径
// 此路由路径将匹配对根路由 /user 的请求;
app.put("/user", (req, res) => {
  res.send("Got a PUT request at /user");
});

app.delete("/user", (req, res) => {
  res.send("Got a DELETE request at /user");
});
// 静态文件
// app.use(express.static("static"))
app.use("/statics", express.static(path.join(__dirname, "static")));

// 此路由路径将匹配 acd 和 abcd
app.get("/ab?cd", (req, res) => {
  res.send("ab?cd");
});
// 此路由路径将匹配 abcd、abbcd、abbbcd 等
app.get("/ab+cd", (req, res) => {
  res.send("ab+cd");
});
// 此路由路径将匹配 abcd、abxcd、abRANDOMcd、ab123cd 等
app.get("/ab*cd", (req, res) => {
  res.send("ab*cd");
});
// 基于正则表达式的路由路径
// 此路由路径将匹配包含“a”的任何内容。
app.get(/a/, (req, res) => {
  res.send("/a/");
});
app.get(/.*fly$/, (req, res) => {
  res.send("/.*fly$/");
});
// Route path: /users/:userId/books/:bookId
// Request URL: https://:3000/users/34/books/8989
// req.params: { "userId": "34", "bookId": "8989" }
app.get("/users/:userId/books/:bookId", (req, res) => {
  res.send(req.params);
});
// Route path: /flights/:from-:to
// Request URL: https://:3000/flights/LAX-SFO
// req.params: { "from": "LAX", "to": "SFO" }

// Route path: /plantae/:genus.:species
// Request URL: https://:3000/plantae/Prunus.persica
// req.params: { "genus": "Prunus", "species": "persica" }

// Route path: /user/:userId(\d+)
// Request URL: https://:3000/user/42
// req.params: {"userId": "42"}
// ---------------------------------

app.get(
  "/example/b",
  (req, res, next) => {
    console.log("the response will be sent by the next function ...");
    next();
  },
  (req, res) => {
    res.send("Hello from B!");
  }
);

// route
app
  .route("/book")
  .get((req, res) => {
    res.send("Get a random book");
  })
  .post((req, res) => {
    res.send("Add a book");
  })
  .put((req, res) => {
    res.send("Update the book");
  });

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
